#ifndef COMPLETEBINARYTREEWINDOW_H
#define COMPLETEBINARYTREEWINDOW_H

#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QGroupBox>
#include <QMessageBox>
#include <QComboBox>
#include <QWidget>
#include <QPainter>
#include <QScrollArea>
#include <QScrollBar>
#include <QTimer>
#include "intarray.h"  // 包含共享的IntArray

class ArrayVisualizationWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ArrayVisualizationWidget(QWidget *parent = nullptr);

    void setArray(const IntArray& array);

    // 遍历可视化相关方法
    void startTraversal(const IntArray& order);
    void nextTraversalStep();
    void resetTraversal();
    bool isTraversing() const { return m_isTraversing; }
    bool isTraversalFinished() const { return m_currentTraverseIndex >= m_traverseOrder.size(); }

    QSize getArraySize() const;

signals:
    void traversalStepCompleted(const QString& currentResult);
    void traversalFinished();

protected:
    void paintEvent(QPaintEvent* event) override;

private:
    void drawArrayElement(QPainter& painter, int value, int index, int x, int y, bool isHighlighted = false);

    IntArray m_array;
    int m_arraySize;

    // 遍历可视化相关成员
    IntArray m_traverseOrder;
    int m_currentTraverseIndex;
    bool m_isTraversing;
};

class CompleteBinaryTreeWindow : public QMainWindow
{
    Q_OBJECT

public:
    CompleteBinaryTreeWindow(QWidget *parent = nullptr);
    ~CompleteBinaryTreeWindow();

signals:
    void returnToMainMenu();

private slots:
    void onInputData();
    void onInsert();
    void onDelete();
    void onTraverse();
    void onClear();
    void onGenerateRandom();
    void onReturnToMainMenu();
    void onTraversalStepCompleted(const QString& currentResult);
    void onTraversalFinished();

private:
    void setupUI();
    void updateDisplay();
    void preorderTraversal(int index, IntArray& result);
    void inorderTraversal(int index, IntArray& result);
    void postorderTraversal(int index, IntArray& result);
    void levelOrderTraversal(IntArray& result);

    // 完全二叉树相关方法
    int getParentIndex(int index) const { return (index - 1) / 2; }
    int getLeftChildIndex(int index) const { return 2 * index + 1; }
    int getRightChildIndex(int index) const { return 2 * index + 2; }
    bool hasLeftChild(int index) const { return getLeftChildIndex(index) < m_treeData.size(); }
    bool hasRightChild(int index) const { return getRightChildIndex(index) < m_treeData.size(); }
    int getTreeHeight() const;

    // 替换随机数生成的函数
    int randomInt(int min, int max);

    IntArray m_treeData;

    QTextEdit *m_display;
    QComboBox *m_traverseCombo;

    ArrayVisualizationWidget *m_visualizationWidget;
    QScrollArea *m_scrollArea;

    // 遍历相关成员
    QTimer *m_traverseTimer;
    QString m_currentTraverseResult;
    bool m_isTraversing;
    int m_traverseSpeed;
};

#endif // COMPLETEBINARYTREEWINDOW_H
